package JDBC;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCLearn1 {
    static Connection conn = null;
    static Statement statement = null;

    static {
        //1.加载驱动
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\JDBC.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String user=properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        //2.获取链接
        try {
            conn = DriverManager.getConnection(url, user, password);
            statement = conn.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void FindAllData() throws ClassNotFoundException, SQLException {
        //3.执行查询
        String sql = "select * from user";
        ResultSet resultSet = statement.executeQuery(sql);
        //4.数据解析
        while (resultSet.next()) {
            System.out.println("resultSet.getInt(\"id\") = " + resultSet.getInt("id"));
            System.out.println("resultSet.getString(\"name\") = " + resultSet.getString("name"));
            System.out.println("resultSet.getString(\"password\") = " + resultSet.getString("password"));
            System.out.println("resultSet.getString(\"nickname\") = " + resultSet.getString("nickname"));
        }
        close();
    }

    @Test
    public void insert(student obj) throws ClassNotFoundException, SQLException {

        String sql = "insert into user values(" + obj.getId() + ",'" + obj.getName() + "','" + obj.getPassword() + "','" + obj.getNickname() + "')";
        System.out.println("sql = " + sql);
        int i = statement.executeUpdate(sql);
        System.out.println("i = " + i);
        close();
    }

    @Test
    public void update(student obj, Integer id) throws SQLException, ClassNotFoundException {

        String sql = "update user set name='" + obj.getName() + "',nickname='" + obj.getNickname() + "' where id=" + id;
        System.out.println("sql = " + sql);
        int i = statement.executeUpdate(sql);
        System.out.println("i = " + i);
        close();
    }

    @Test
    public void Delete(Integer id) throws ClassNotFoundException, SQLException {
        String sql = "Delete from user where id=" + id;
        System.out.println("sql = " + sql);
        int i = statement.executeUpdate(sql);
        System.out.println("i = " + i);
        close();
    }


    public void close() throws SQLException {
        statement.close();
        conn.close();
    }
}
